package jwt

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go/v4"
)

var mySigningKey = []byte("ming12/19")

type MyCustomClaims struct {
	UserId int64 `json:"user_id"`
	jwt.StandardClaims
}

// CreateToken 生产token
func CreateToken(claims *MyCustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)
	fmt.Printf("%v %v", ss, err)
	return ss, err
}

// ParesToken 验证token
func ParesToken(text string) (int64, int64, error) {
	if len(text) == 0 {
		return 0, 0, errors.New("请先登录！！！")
	}
	//var str string
	//strArr := strings.Split(text, " ")
	//fmt.Println(strArr[1])

	token, err := jwt.ParseWithClaims(text, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		//返回 key
		return mySigningKey, nil
	})

	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Printf("%v %v", claims.UserId, claims.StandardClaims.ExpiresAt.Unix())
		return claims.UserId, claims.StandardClaims.ExpiresAt.Unix(), nil
	} else {
		fmt.Println(err)
		return 0, 0, errors.New("token解析失败！！！")
	}
}
